package ex4.multiThread;

class MyThread8 implements Runnable {
	private int ticket = 5; // 一共有5张票

	@Override
	public void run() {
		for (int x = 0; x < 20; x++) {
			this.sale(); // 卖票操作
		}
	}

	public synchronized void sale() { // 同步方法
		if (this.ticket > 0) { // 判断当前是否还有剩余票
			try {
				Thread.sleep(1000); // 休眠1秒，模拟延迟
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + " 卖票，ticket = " + this.ticket--);
		}
	}
}

public class TestDemo8 {
	public static void main(String[] args) throws Exception {
		MyThread8 mt = new MyThread8();
		new Thread(mt, "票贩子A").start(); // 启动多线程
		new Thread(mt, "票贩子B").start(); // 启动多线程
		new Thread(mt, "票贩子C").start(); // 启动多线程
		new Thread(mt, "票贩子D").start(); // 启动多线程
	}
}